package pl.edu.pw.polygen.db.dao;

import java.sql.SQLException;
import java.util.List;

import org.dozer.DozerBeanMapper;
import org.hibernate.Criteria;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Restrictions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.orm.hibernate3.HibernateCallback;
import org.springframework.stereotype.Repository;

import pl.edu.pw.polygen.beans.FileBean;
import pl.edu.pw.polygen.db.dao.generic.GenericDaoImpl;
import pl.edu.pw.polygen.db.entieties.PolyFile;

@Repository("polyFileDao")
public class PolyFileDaoImpl extends GenericDaoImpl<PolyFile, Long> implements PolyFileDao {

	@Autowired
	private DozerBeanMapper mapper;
	
	public boolean isExisting(FileBean fileBean) {
		final PolyFile polyFile = mapper.map(fileBean, PolyFile.class);
		return getHibernateTemplate().execute(new HibernateCallback<Boolean>() {
			public Boolean doInHibernate(Session session) throws HibernateException, SQLException {
				Criteria criteria = session.createCriteria(PolyFile.class).add(Restrictions.eq("project", polyFile.getProject() )).add(Restrictions.eq("fileName", polyFile.getFileName()));
				List<PolyFile> projects = criteria.list();
				if(projects!=null && projects.size()>0){
					return true;
				}else{
					return false;
				}
			}
		});
	}

	public FileBean saveFile(FileBean fileBean) {
		PolyFile file = mapper.map(fileBean, PolyFile.class);
		saveOrUpdate(file);
		fileBean= mapper.map(file, FileBean.class);
		return fileBean;
	}
 
	public void removeFile(FileBean fileBean) {
		final PolyFile polyFile = mapper.map(fileBean, PolyFile.class);
		delete(polyFile);
	}
	

	public FileBean findFile(final String fileName, final String projectName, final Long userId) {
		return getHibernateTemplate().execute(new HibernateCallback<FileBean>() {
			public FileBean doInHibernate(Session session) throws HibernateException, SQLException {
						Criteria criteria = session
								.createCriteria(PolyFile.class).createAlias("project", "p")
								.createAlias("p.user", "u")
								.add(Restrictions.eq("p.name",
										projectName))
								.add(Restrictions.eq("fileName", fileName))
								.add(Restrictions.eq("u.id", userId));
						PolyFile file = (PolyFile) criteria.uniqueResult();
						return mapper.map(file, FileBean.class);
			}
		});
	}

	public FileBean findFile(Long projectId) {
		return mapper.map(getById(projectId), FileBean.class);
	}
	
	
}
